package com.cxx.factory;

import com.cxx.annotation.Autowired;
import com.cxx.annotation.Service;
import com.cxx.annotation.Transactional;
import com.cxx.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * 代理工厂，用于事务控制
 *
 * @author Shuhang He
 * @version 1.0
 * @date 2021/3/14 21:45
 */
public class ProxyFactory {

    @Autowired
    private TransactionManager transactionManager;


    /**
     * 获取JDK动态代理对象
     * 注意： 传进来的对象必须实现一个接口
     * @param object 原对象
     * @return 代理后的对象
     */
    public Object getJDKProxy(Object object) {

        return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), (proxy, method, args) -> {
            Object result;

            try {
                // 开启手动事务
                transactionManager.begin();
                result = method.invoke(object, args);
                transactionManager.commit();
                transactionManager.close();
            } catch (Exception e) {
                e.printStackTrace();
                transactionManager.rollback();
                throw e;
            }

            return result;
        });
    }

    /**
     * 获取cglib动态代理对象
     * @param object 原对象
     * @return 代理后的对象
     */
    public Object getCglibProxy(Object object) {
        return Enhancer.create(object.getClass(), (MethodInterceptor) (o, method, objects, methodProxy) -> {
            Object result;

            try {
                // 开启手动事务
                transactionManager.begin();
                result = method.invoke(object, objects);
                transactionManager.commit();
                transactionManager.close();
            } catch (Exception e) {
                e.printStackTrace();
                transactionManager.rollback();
                throw e;
            }

            return result;
        });
    }

    /**
     * 获取JDK动态代理对象（某些特定方法开启事务）
     * 注意： 传进来的对象必须实现一个接口
     * @param object 原对象
     * @return 代理后的对象
     */
    public Object getSomeMethodJDKProxy(Object object, List<String> methods) {

        return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), (proxy, method, args) -> {
            Object result;
            if (methods.contains(method.getName())) {
               result = transactionBegin(object, method, args);
            } else {
                result = method.invoke(object, args);
            }

            return result;
        });
    }

    /**
     * 获取cglib动态代理对象（某些特定方法开启事务）
     * @param object 原对象
     * @return 代理后的对象
     */
    public Object getSomeMethodCglibProxy(Object object, List<String> methods) {
        return Enhancer.create(object.getClass(), (MethodInterceptor) (o, method, objects, methodProxy) -> {
            Object result;
            if (methods.contains(method.getName())) {
                result = transactionBegin(object, method, objects);
            } else {
                result = method.invoke(object, objects);
            }
            return result;
        });
    }

    private Object transactionBegin(Object object, Method method, Object[] args) throws SQLException, InvocationTargetException, IllegalAccessException {
        Object result;
        try {
            // 开启手动事务
            transactionManager.begin();
            result = method.invoke(object, args);
            transactionManager.commit();
            transactionManager.close();
        } catch (Exception e) {
            e.printStackTrace();
            transactionManager.rollback();
            throw e;
        }

        return result;
    }
}
